package logo

import (
	"bufio"
	"fmt"
	"io"
	"os"
	"strings"
)

const (
	isseDB    = "isseDB"
	issedb    = "issedb"
	oldLog    = "gs_"
	openGauss = "openGauss"
	opengauss = "opengauss"
)

var (
	openGaussNum = 0
	opengaussNum = 0
)

func replaceContent(filePath string) error {
	f, err := os.OpenFile(filePath, os.O_RDWR, 0644)
	if err != nil {
		errMsg := fmt.Errorf("openFile: %s ailed, %s", filePath, err.Error())
		fmt.Println(errMsg)
		return err
	}

	defer f.Close()

	bfRead := bufio.NewReader(f)
	buf := make([]byte, 0)
	count := 0
	for {
		line, err := bfRead.ReadBytes('\n')
		if err != nil {
			if err == io.EOF {
				line = hookReplaceGs(line, oldLog, targetLogo)
				line, count = hookReplaceGauss(line, openGauss, isseDB)
				openGaussNum += count
				line, count = hookReplaceGauss(line, opengauss, issedb)
				opengaussNum += count
				buf = append(buf, line...)
				break
			}
			panic(err)
		}
		line = hookReplaceGs(line, oldLog, targetLogo)
		line, count = hookReplaceGauss(line, openGauss, isseDB)
		openGaussNum += count
		line, count = hookReplaceGauss(line, opengauss, issedb)
		opengaussNum += count
		buf = append(buf, line...)
	}
	//buf = ReplaceOpenGauss(buf)
	err = os.WriteFile(filePath, buf, 655)
	return err
}

// hookReplaceGs, replace [^a-zA-Z]gs_ | ^gs_
func hookReplaceGs(line []byte, old, target string) []byte {
	block := len(old)
	var bufTemp []byte
	for strings.Contains(string(line), old) {
		x := strings.Index(string(line), old)
		if x > 0 {
			if (line[x-1] >= 65 && line[x-1] <= 90) || (line[x-1] >= 97 && line[x-1] <= 122) {
				bufTemp = append(bufTemp, line[0:x+block]...)
				line = line[x+block:]
				continue
			}
			bufTemp = append(bufTemp, line[0:x]...)
		}
		matchContentCount++
		bar.Play(matchContentCount)
		bufTemp = append(bufTemp, target...)
		line = line[x+block:]
	}
	bufTemp = append(bufTemp, line...)
	return bufTemp
}

// hookReplaceGauss replace openGauss
func hookReplaceGauss(line []byte, old, target string) ([]byte, int) {
	var count int
	var bufTemp []byte
	block := len(old)
	for strings.Contains(string(line), old) {
		x := strings.Index(string(line), old)
		if x > 0 {
			bufTemp = append(bufTemp, line[0:x]...)
		}
		bufTemp = append(bufTemp, target...)
		line = line[x+block:]
		count++
	}
	bufTemp = append(bufTemp, line...)
	return bufTemp, count
}
